import { getTenantId } from "/@/utils/tenant"
import { getUrlParam } from "/@/utils/index"
import { initSecretInfo } from "/@/utils/encrypt-key"
import { useMessage } from "/@/hooks/web/useMessage"
import { useGlobSetting } from "/@/hooks/setting"
import * as appApi from "/@/api/iam/app"
import { defineStore } from "pinia"
import { store } from "/@/store"
import * as appCache from "/@/utils/cache/module/iam"
import { useIam } from "/@/hooks/web/useIam"

const glob = useGlobSetting()
const { createErrorModal } = useMessage()

interface AppState {
  appPublicConfig?: any
}

function getUserId() {
  const href = decodeURIComponent(window.location.href)
  return getUrlParam("user_id", href)  || getUrlParam("userId", href) 
}

export const useIamStore = defineStore({
  id: "iam",
  state: (): AppState => ({
    appPublicConfig: {}
  }),
  getters: {
    getAppPublicConfig(): any {
      return this.appPublicConfig || appCache.getPublicConfig()
    }
  },
  actions: {
    async initAppPublicConfig() {
      console.log('pageUrl', window.location.href)
      const appId = useIam().getAppId() as string
      const userId = getUserId() as string
      const tenantId = getTenantId() as string
      let publicConfig : any  = null
      console.log('appId', appId)
      if (appId) {
        appCache.setAppId(appId)
        publicConfig = await appApi.getPublicConfig({ appId, tenantId, userId })
      
        if(publicConfig?.maintenanceFlag) {
          window.location.href = `${glob.domainUrl}/systemMaintenance`
        }
      
        console.log("---------------- configValue ", publicConfig)
        appCache.savePublicConfig(appId, publicConfig)
        this.appPublicConfig = publicConfig
      }
    
      const encryptSecretInfo = publicConfig?.sysEncryptSecretInfo
      if (!encryptSecretInfo) {
        createErrorModal({ title: "加载失败", content: "密钥数据为空" })
        throw new Error("密钥初始化失败")
      }
    
      const ret = await initSecretInfo(publicConfig.sysEncryptSecretInfo)
      if (!ret) {
        createErrorModal({ title: "加载失败", content: "密钥初始化失败, 请联系管理员" })
        throw new Error("密钥初始化失败")
      }
      return this.appPublicConfig
    }
  },
})

// Need to be used outside the setup
export function useIamStoreWithOut() {
  return useIamStore(store)
}
